#include "roundmenuwidget.h"
#include <QRandomGenerator>
#include <QDebug>

RoundMenuWidget::RoundMenuWidget(QWidget *parent)
    : QWidget(parent)
    , m_isPopup(false)
    , m_centerBtnSize(64)
    , m_itemType(0)
    , m_isExpanded(false)
    , m_rotationAngle(0.0)
    , m_expandProgress(0.0)
    , m_gatherProgress(0.0)  // 初始化聚集进度
    , m_hoveredItem(-1)
    , m_centerButtonHovered(false)
    , m_isDragging(false)
{
    initRoundMenuCtl();
}

RoundMenuWidget::RoundMenuWidget(bool popup, uint btnSize, uint itemType, QWidget *parent)
    : QWidget(parent)
    , m_isPopup(popup)
    , m_centerBtnSize(btnSize)
    , m_itemType(itemType)
    , m_isExpanded(false)
    , m_rotationAngle(0.0)
    , m_expandProgress(0.0)
    , m_gatherProgress(0.0)  // 初始化聚集进度
    , m_hoveredItem(-1)
    , m_centerButtonHovered(false)
    , m_isDragging(false)
{
    initRoundMenuCtl();
}

RoundMenuWidget::~RoundMenuWidget()
{
    qDeleteAll(m_menuItems);
    m_menuItems.clear();
}

void RoundMenuWidget::initRoundMenuCtl()
{
    // 设置控件属性
    setMouseTracking(true);
    setAttribute(Qt::WA_TranslucentBackground);
    setMinimumSize(200, 200);
    
    // 初始化动画组
    m_menuAnimeGroup = new QParallelAnimationGroup(this);
    m_hoverAnimeGroup = new QSequentialAnimationGroup(this);
      // 初始化属性动画
    m_rotationAnimation = new QPropertyAnimation(this, "rotationAngle", this);
    m_rotationAnimation->setDuration(m_style.animationDuration);
    m_rotationAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    m_expandAnimation = new QPropertyAnimation(this, "expandProgress", this);
    m_expandAnimation->setDuration(m_style.animationDuration);
    m_expandAnimation->setEasingCurve(QEasingCurve::OutBack);
    
    // 初始化聚集动画
    m_gatherAnimation = new QPropertyAnimation(this, "gatherProgress", this);
    m_gatherAnimation->setDuration(m_style.animationDuration);
    m_gatherAnimation->setEasingCurve(QEasingCurve::InOutQuad);
    
    // 初始化定时器
    m_rotationTimer = new QTimer(this);
    m_waveTimer = new QTimer(this);
    
    // 连接信号
    connect(m_rotationTimer, &QTimer::timeout, this, &RoundMenuWidget::onRotationUpdate);
    connect(m_waveTimer, &QTimer::timeout, this, &RoundMenuWidget::onRotationUpdate);
    connect(m_expandAnimation, &QPropertyAnimation::finished, this, &RoundMenuWidget::onAnimationFinished);
    
    initMenuAnimation();
    
    // 设置默认图标路径
    m_expandImgPath = "";
    m_closedImgPath = "";
}

void RoundMenuWidget::initMenuAnimation()
{
    m_menuAnimeGroup->clear();
    m_menuAnimeGroup->addAnimation(m_rotationAnimation);
    m_menuAnimeGroup->addAnimation(m_expandAnimation);
}

void RoundMenuWidget::addMenuItem(const QString& title, const QString& tooltip, 
                                 const QPixmap& icon, const QColor& backgroundColor)
{
    MenuItemData* item = new MenuItemData(title, tooltip, icon, backgroundColor);
    m_menuItems.append(item);
    update();
}

void RoundMenuWidget::addMenuItem(const MenuItemData& item)
{
    MenuItemData* newItem = new MenuItemData(item);
    m_menuItems.append(newItem);
    update();
}

// 新增：支持两个图标状态的重载方法
void RoundMenuWidget::addMenuItem(const QString& title, const QString& tooltip, 
                                 const QString& iconPath, const QString& hoverIconPath,
                                 const QColor& backgroundColor)
{
    QPixmap icon;
    QPixmap hoverIcon;
    
    // 加载图标
    if (!iconPath.isEmpty()) {
        icon = QPixmap(iconPath);
    }
    if (!hoverIconPath.isEmpty()) {
        hoverIcon = QPixmap(hoverIconPath);
    }
    
    MenuItemData* item = new MenuItemData(title, tooltip, icon, backgroundColor, hoverIcon, hoverIcon);
    m_menuItems.append(item);
    update();
}

void RoundMenuWidget::insertMenuItem(int index, const MenuItemData& item)
{
    if (index < 0 || index > m_menuItems.count()) {
        return;
    }
    MenuItemData* newItem = new MenuItemData(item);
    m_menuItems.insert(index, newItem);
    update();
}

void RoundMenuWidget::removeMenuItem(int index)
{
    if (index < 0 || index >= m_menuItems.count()) {
        return;
    }
    delete m_menuItems.at(index);
    m_menuItems.removeAt(index);
    update();
}

void RoundMenuWidget::clearMenuItems()
{
    qDeleteAll(m_menuItems);
    m_menuItems.clear();
    update();
}

void RoundMenuWidget::setMenuStyle(const MenuStyleConfig& style)
{
    m_style = style;
    m_rotationAnimation->setDuration(m_style.animationDuration);
    m_expandAnimation->setDuration(m_style.animationDuration);
    m_gatherAnimation->setDuration(m_style.animationDuration);  // 同步聚集动画时长
    update();
}

void RoundMenuWidget::setExpandIcon(const QString& iconPath)
{
    m_expandImgPath = iconPath;
    update();
}

void RoundMenuWidget::setCollapseIcon(const QString& iconPath)
{
    m_closedImgPath = iconPath;
    update();
}

void RoundMenuWidget::expandMenu()
{
    if (m_isExpanded) return;
    
    m_isExpanded = true;
    m_expandAnimation->setStartValue(0.0);
    m_expandAnimation->setEndValue(1.0);
    
    // 简化动画逻辑，避免复杂的动画序列
    if (m_style.enableRotationAnimation && !m_style.useScatteredLayout) {
        m_rotationAnimation->setStartValue(m_rotationAngle);
        m_rotationAnimation->setEndValue(m_rotationAngle + 360.0);
        m_menuAnimeGroup->start();
    } else {
        m_expandAnimation->start();
    }
    
    emit menuExpanded();
    emit menuToggled(true);
}

void RoundMenuWidget::collapseMenu()
{
    if (!m_isExpanded) return;
    
    m_isExpanded = false;
    m_expandAnimation->setStartValue(1.0);
    m_expandAnimation->setEndValue(0.0);
    
    // 简化动画逻辑
    if (m_style.enableRotationAnimation && !m_style.useScatteredLayout) {
        m_rotationAnimation->setStartValue(m_rotationAngle);
        m_rotationAnimation->setEndValue(m_rotationAngle - 360.0);
        m_menuAnimeGroup->start();
    } else {
        m_expandAnimation->start();
    }
    
    emit menuCollapsed();
    emit menuToggled(false);
}

void RoundMenuWidget::toggleMenu()
{
    if (m_isExpanded) {
        collapseMenu();
    } else {
        expandMenu();
    }
}

void RoundMenuWidget::setRotationAngle(qreal angle)
{
    m_rotationAngle = angle;
    update();
}

void RoundMenuWidget::setExpandProgress(qreal progress)
{
    m_expandProgress = qBound(0.0, progress, 1.0);
    update();
}

void RoundMenuWidget::setGatherProgress(qreal progress)
{
    m_gatherProgress = qBound(0.0, progress, 1.0);
    update();
}

void RoundMenuWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
    
    // 设置合成模式以避免分层窗口问题
    painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
    
    // 绘制背景
    if (m_style.showBackground) {
        drawBackground(&painter);
    }
    
    // 绘制菜单项
    if (m_expandProgress > 0.0) {
        drawMenuItems(&painter);
        
        if (m_style.showSeparatorLines && !m_style.useRoundMenuItems) {
            drawSeparatorLines(&painter);
        }
    }    // 绘制中心按钮
    if (m_style.showCenterButton || (m_style.useScatteredLayout && m_style.showCenterButtonInScattered)) {
        drawCenterButton(&painter);
    }
}


void RoundMenuWidget::drawBackground(QPainter *painter)
{
    painter->setPen(m_style.showBorder ? QPen(m_style.borderColor, m_style.borderWidth) : Qt::NoPen);
    
    // 绘制渐变背景或纯色背景
    if (!m_style.gradientColors.isEmpty()) {
        QLinearGradient gradient(QPoint(0, 0), QPoint(width(), height()));
        for (const auto& gradientData : m_style.gradientColors) {
            gradient.setColorAt(gradientData.position, gradientData.color);
        }
        painter->setBrush(gradient);
    } else {
        painter->setBrush(m_style.menuBackgroundColor);
    }
    
    QRectF rect = this->rect();
    uint minVal = qMin(width(), height());
    rect.setSize(QSize(minVal * m_style.outerRadiusScale, minVal * m_style.outerRadiusScale));
    rect.moveCenter(getCenter());
    painter->drawEllipse(rect);
}

void RoundMenuWidget::drawMenuItems(QPainter *painter)
{
    if (m_menuItems.isEmpty()) return;
    
    if (m_style.useScatteredLayout) {
        // 分散布局 - 类似第一张图的效果
        drawScatteredMenuItems(painter);
    } else {
        // 传统圆形布局
        drawCircularMenuItems(painter);
    }
}

void RoundMenuWidget::drawScatteredMenuItems(QPainter *painter)
{
    if (m_menuItems.isEmpty()) return;
    
    int count = m_menuItems.count();
    QFont font = this->font();
    
    // 获取分散布局和圆形布局的位置
    QList<QPointF> scatteredPositions = getScatteredPositions(count);
    QList<QPointF> circularPositions = getCircularPositions(count);
    
    qreal itemSize = qMin(width(), height()) * 0.12; // 固定大小的圆形图标
    
    for (int i = 0; i < count && i < scatteredPositions.size() && i < circularPositions.size(); ++i) {
        MenuItemData* item = m_menuItems.at(i);
        
        // 计算插值位置（从分散到圆形的过渡）
        QPointF scatteredPos = scatteredPositions[i];
        QPointF circularPos = circularPositions[i];
        QPointF currentPos = scatteredPos + (circularPos - scatteredPos) * m_gatherProgress;
        
        // 应用展开动画
        if (m_expandProgress < 1.0) {
            qreal scale = m_expandProgress;
            QPointF widgetCenter = getCenter();
            QPointF offset = currentPos - widgetCenter;
            currentPos = widgetCenter + offset * scale;
        }
        
        QRectF iconRect(currentPos.x() - itemSize/2, currentPos.y() - itemSize/2, itemSize, itemSize);
        
        // 获取背景颜色
        QColor bgColor = item->backgroundColor;
        if (!bgColor.isValid()) {
            bgColor = m_style.menuItemBackgroundColor;
        }
          // 绘制圆形背景 - 保持白色，不变化
        painter->setBrush(bgColor); // 移除hover状态的颜色变化
        painter->setPen(Qt::NoPen);
        painter->drawEllipse(iconRect);
        
        // 绘制文字
        if (!item->title.isEmpty()) {
            QRectF textRect = iconRect.adjusted(iconRect.width() * 0.1, iconRect.height() * 0.1,
                                              -iconRect.width() * 0.1, -iconRect.height() * 0.1);            font.setPointSizeF(iconRect.height() / 8.0);
            font.setBold(true);
            painter->setFont(font);
            painter->setPen(QColor(29, 27, 32));  // Material On Surface
            
            QString displayText = item->title.length() > 6 ? item->title.left(6) : item->title;
            painter->drawText(textRect, Qt::AlignCenter | Qt::TextWordWrap, displayText);
        }
    }
}

void RoundMenuWidget::drawCircularMenuItems(QPainter *painter)
{
    if (m_menuItems.isEmpty()) return;
    
    int count = m_menuItems.count();
    qreal outerRadius = getOuterRadius();
    qreal innerRadius = getInnerRadius();
    
    QFont font = this->font();
    
    for (int i = 0; i < count; ++i) {
        MenuItemData* item = m_menuItems.at(i);
        
        auto path = getMenuItemPath(i);
        
        // 计算背景颜色
        QColor bgColor = m_style.useRandomColors ? 
            QColor::fromHsl(QRandomGenerator::global()->bounded(360), 
                           QRandomGenerator::global()->bounded(256), 
                           QRandomGenerator::global()->bounded(200)) : 
            item->backgroundColor;
          if (!bgColor.isValid()) {
            bgColor = m_style.menuItemBackgroundColor;
        }
          // 对于圆形菜单项，计算动态大小
        qreal iconRectWidth = (outerRadius - innerRadius) * m_expandProgress;
          // 绘制菜单项背景
        if (!m_style.useRoundMenuItems) {
            // 扇形菜单项 - 保持白色背景
            painter->fillPath(path, bgColor); // 移除hover状态的颜色变化
        } else {
            // 圆形菜单项
            QRectF rectBtnBkg(0, 0, iconRectWidth / m_style.menuItemBgScale, iconRectWidth / m_style.menuItemBgScale);
            rectBtnBkg.moveCenter(path.boundingRect().center());
            
            // 绘制发光效果
            if (m_style.enableGlowEffect && item->isHovered) {
                painter->save();
                QRectF glowRect = rectBtnBkg.adjusted(-5, -5, 5, 5);
                QRadialGradient glowGradient(glowRect.center(), glowRect.width() / 2.0);
                glowGradient.setColorAt(0, m_style.glowColor);
                glowGradient.setColorAt(1, QColor(m_style.glowColor.red(), m_style.glowColor.green(), 
                                                 m_style.glowColor.blue(), 0));
                painter->setBrush(glowGradient);
                painter->setPen(Qt::NoPen);
                painter->drawEllipse(glowRect);
                painter->restore();
            }            
            painter->setBrush(bgColor); // 移除hover状态的颜色变化，保持白色
            painter->setPen(Qt::NoPen);
            painter->drawEllipse(rectBtnBkg);
        }        // 绘制图标或文字
        QPixmap iconToShow;
        if (item->isPressed && !item->pressedIcon.isNull()) {
            iconToShow = item->pressedIcon;
        } else if (item->isHovered && !item->hoverIcon.isNull()) {
            iconToShow = item->hoverIcon;
        } else if (!item->icon.isNull()) {
            iconToShow = item->icon;
        }
        
        if (!iconToShow.isNull()) {
            QRectF rectIcon(0, 0, iconRectWidth / m_style.menuItemScale, iconRectWidth / m_style.menuItemScale);
            rectIcon.moveCenter(path.boundingRect().center());
            painter->drawPixmap(rectIcon, iconToShow, iconToShow.rect());
        } else if (!item->title.isEmpty()) {
            QRectF rectText(0, 0, iconRectWidth / m_style.menuItemScale * 0.8, iconRectWidth / m_style.menuItemScale * 0.8);
            rectText.moveCenter(path.boundingRect().center());
            font.setPointSizeF(rectText.height() / 5.0);            font.setBold(true);
            painter->setFont(font);
            painter->setPen(QColor(29, 27, 32));  // Material On Surface
            
            QString displayText = m_style.showFullNameWithoutIcon ? item->title : item->title.left(8);
            painter->drawText(rectText, Qt::AlignCenter | Qt::TextWordWrap, displayText);
        }
    }
}

void RoundMenuWidget::drawCenterButton(QPainter *painter)
{
    auto path = getCenterButtonPath();
    
    QColor buttonColor = m_centerButtonHovered ? m_style.centerButtonHoverColor :
                        (m_isExpanded ? m_style.centerButtonExpandColor : m_style.centerButtonColor);
    
    painter->setBrush(buttonColor);
    painter->setPen(m_style.showBorder ? QPen(m_style.borderColor, m_style.borderWidth) : Qt::NoPen);
    painter->drawPath(path);
    
    // 绘制中心按钮图标或文字
    auto rect = path.boundingRect();
    
    QPixmap pixmap = m_isExpanded ? QPixmap(m_closedImgPath) : QPixmap(m_expandImgPath);
    
    if (!pixmap.isNull()) {
        rect = rect.marginsRemoved(QMargins(rect.width() / 4.0, rect.height() / 4.0,
                                          rect.width() / 4.0, rect.height() / 4.0));
        painter->drawPixmap(rect, pixmap, pixmap.rect());
    } else {
        rect = rect.marginsRemoved(QMargins(rect.width() / 4.0, rect.height() / 4.0,
                                          rect.width() / 4.0, rect.height() / 4.0));
        
        QString switchText = m_isExpanded ? "CLOSE" : "MENU";
        
        QFont font = this->font();
        font.setPointSizeF(rect.height() / 4.0);
        painter->setFont(font);
        painter->setPen(m_centerButtonHovered ? m_style.menuItemTextColor : m_style.menuItemTextHoverColor);
        painter->drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, switchText);
    }
}

void RoundMenuWidget::drawSeparatorLines(QPainter *painter)
{
    if (m_menuItems.isEmpty()) return;
    
    int count = m_menuItems.count();
    qreal radian = 2 * M_PI / count;
    qreal outerRadius = getOuterRadius() * m_expandProgress;
    qreal innerRadius = getInnerRadius() * m_expandProgress;
    
    painter->save();
    painter->setPen(QPen(m_style.borderColor, m_style.borderWidth));
    
    for (int i = 0; i < count; ++i) {
        QPointF point1(getCenter().x() + outerRadius * std::cos(radian * i + getStartRadian()),
                      getCenter().y() - outerRadius * std::sin(radian * i + getStartRadian()));
        QPointF point2(getCenter().x() + innerRadius * std::cos(radian * i + getStartRadian()),
                      getCenter().y() - innerRadius * std::sin(radian * i + getStartRadian()));
        
        painter->drawLine(point1, point2);
    }
    
    painter->restore();
}

void RoundMenuWidget::mousePressEvent(QMouseEvent *event)
{
    m_lastMousePos = event->pos();
    m_isDragging = false;
    
    // 检查中心按钮
    if (isPointInCenterButton(event->pos())) {
        return;
    }
    
    // 检查菜单项并设置按下状态
    if (m_isExpanded) {
        int itemIndex = getMenuItemAtPosition(event->pos());
        if (itemIndex >= 0 && itemIndex < m_menuItems.size()) {
            // 清除所有按下状态
            for (auto* item : m_menuItems) {
                item->isPressed = false;
            }
            // 设置当前项为按下状态
            m_menuItems[itemIndex]->isPressed = true;
            update();
            return;
        }
    }
    
    QWidget::mousePressEvent(event);
}

void RoundMenuWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_isDragging && (event->pos() - m_lastMousePos).manhattanLength() > 3) {
        m_isDragging = true;
    }
    
    updateMenuItemStates();
    
    QWidget::mouseMoveEvent(event);
}

void RoundMenuWidget::mouseReleaseEvent(QMouseEvent *event)
{
    // 清除所有按下状态
    for (auto* item : m_menuItems) {
        item->isPressed = false;
    }
    
    if (!m_isDragging) {
        // 检查中心按钮点击
        if (isPointInCenterButton(event->pos())) {
            toggleMenu();
            update();
            return;
        }
        
        // 检查菜单项点击
        if (m_isExpanded) {
            int itemIndex = getMenuItemAtPosition(event->pos());
            if (itemIndex >= 0) {
                emit menuItemClicked(itemIndex);
                update();
                return;
            }
        }
    }
    
    m_isDragging = false;
    update();
    QWidget::mouseReleaseEvent(event);
}

void RoundMenuWidget::leaveEvent(QEvent *event)
{
    m_hoveredItem = -1;
    m_centerButtonHovered = false;
    
    // 清除所有悬停状态和按下状态
    for (auto* item : m_menuItems) {
        item->isHovered = false;
        item->isPressed = false;
    }
    
    update();
    QWidget::leaveEvent(event);
}

void RoundMenuWidget::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event)
    update();
}

void RoundMenuWidget::onRotationUpdate()
{
    // 可以在这里添加额外的旋转更新逻辑
    update();
}

void RoundMenuWidget::onAnimationFinished()
{
    // 动画完成后的清理工作
    if (!m_isExpanded && m_expandProgress <= 0.0) {
        // 菜单完全收起后重置悬停状态
        for (auto* item : m_menuItems) {
            item->isHovered = false;
        }
    }
    update();
}

void RoundMenuWidget::updateMenuItemStates()
{
    if (!m_isExpanded) return;
    
    QPoint mousePos = mapFromGlobal(QCursor::pos());
    
    // 更新中心按钮悬停状态
    bool centerHovered = isPointInCenterButton(mousePos);
    if (centerHovered != m_centerButtonHovered) {
        m_centerButtonHovered = centerHovered;
        update();
    }
    
    // 更新菜单项悬停状态
    int hoveredItem = getMenuItemAtPosition(mousePos);
    if (hoveredItem != m_hoveredItem) {
        // 清除之前的悬停状态
        if (m_hoveredItem >= 0 && m_hoveredItem < m_menuItems.count()) {
            m_menuItems[m_hoveredItem]->isHovered = false;
        }
        
        // 设置新的悬停状态
        if (hoveredItem >= 0 && hoveredItem < m_menuItems.count()) {
            m_menuItems[hoveredItem]->isHovered = true;
        }
        
        m_hoveredItem = hoveredItem;
        update();
    }
}

qreal RoundMenuWidget::getOuterRadius() const
{
    uint minVal = qMin(width(), height());
    return minVal * m_style.outerRadiusScale / 2.0;
}

qreal RoundMenuWidget::getInnerRadius() const
{
    uint minVal = qMin(width(), height());
    return minVal * m_style.innerRadiusScale / 2.0;
}

qreal RoundMenuWidget::getCenterButtonRadius() const
{
    // 让中心按钮大小与菜单项大小保持一致
    qreal outerRadius = getOuterRadius();
    qreal innerRadius = getInnerRadius();
    qreal iconRectWidth = (outerRadius - innerRadius);
    return iconRectWidth / m_style.centerButtonScale / 2.0;
}

qreal RoundMenuWidget::getDragAreaRadius() const
{
    uint minVal = qMin(width(), height());
    return minVal / DRAG_AREA_SCALE / 2.0;
}

QPointF RoundMenuWidget::getCenter() const
{
    return QPointF(width() / 2.0, height() / 2.0);
}

QPainterPath RoundMenuWidget::getCenterButtonPath() const
{
    QPainterPath path;
    qreal radius = getCenterButtonRadius();
    QRectF rect(-radius, -radius, radius * 2, radius * 2);
    rect.moveCenter(getCenter());
    path.addEllipse(rect);
    return path;
}

QPainterPath RoundMenuWidget::getMenuItemPath(int index, bool useHoverState) const
{
    QPainterPath path;
    
    if (m_menuItems.isEmpty()) return path;
    
    int count = m_menuItems.count();
    qreal radian = 2 * M_PI / count;
    qreal outerRadius = getOuterRadius() * m_expandProgress;
    qreal innerRadius = getInnerRadius() * m_expandProgress;
    qreal startAngle = getItemAngle(index);
    
    QPointF center = getCenter();
      if (m_style.useRoundMenuItems) {
        // 圆形菜单项 - 返回菜单项中心的圆形区域
        qreal itemRadius = (outerRadius + innerRadius) / 2.0;
        QPointF itemCenter(center.x() + itemRadius * std::cos(startAngle),
                          center.y() - itemRadius * std::sin(startAngle));
        
        // 使用固定的圆形半径，避免重叠
        qreal circleRadius = qMin(width(), height()) * 0.06; // 固定大小，确保不重叠
        if (useHoverState && m_menuItems[index]->isHovered) {
            circleRadius *= 1.1; // 悬停时稍微放大
        }
        
        path.addEllipse(itemCenter, circleRadius, circleRadius);
    } else {
        // 扇形菜单项
        QRectF outerRect(-outerRadius, -outerRadius, outerRadius * 2, outerRadius * 2);
        QRectF innerRect(-innerRadius, -innerRadius, innerRadius * 2, innerRadius * 2);
        outerRect.moveCenter(center);
        innerRect.moveCenter(center);
        
        qreal startAngleDeg = qRadiansToDegrees(startAngle - radian / 2.0);
        qreal spanAngleDeg = qRadiansToDegrees(radian);
        
        path.arcMoveTo(outerRect, startAngleDeg);
        path.arcTo(outerRect, startAngleDeg, spanAngleDeg);
        path.arcTo(innerRect, startAngleDeg + spanAngleDeg, -spanAngleDeg);
        path.closeSubpath();
    }
    
    return path;
}

QRectF RoundMenuWidget::getMenuItemRect(int index) const
{
    return getMenuItemPath(index).boundingRect();
}

qreal RoundMenuWidget::getItemAngle(int index) const
{
    if (m_menuItems.isEmpty()) return 0.0;
    
    int count = m_menuItems.count();
    qreal radian = 2 * M_PI / count;
    return radian * index + getStartRadian() + qDegreesToRadians(m_rotationAngle);
}

qreal RoundMenuWidget::getStartRadian() const
{
    return qDegreesToRadians(m_style.startAngle);
}

int RoundMenuWidget::getMenuItemAtPosition(const QPointF& pos) const
{
    if (!m_isExpanded || m_expandProgress <= 0.0) return -1;
    
    for (int i = 0; i < m_menuItems.count(); ++i) {
        QPainterPath path = getMenuItemPath(i);
        if (path.contains(pos)) {
            return i;
        }
    }
    
    return -1;
}

bool RoundMenuWidget::isPointInCenterButton(const QPointF& pos) const
{
    if (m_style.showCenterButton || (m_style.useScatteredLayout && m_style.showCenterButtonInScattered)) {
        QPainterPath path = getCenterButtonPath();
        return path.contains(pos);
    }
    return false;
}

bool RoundMenuWidget::isPointInDragArea(const QPointF& pos) const
{
    // 拖动区域比中心按钮稍大，方便用户拖动
    QPointF center = getCenter();
    qreal dragRadius = getCenterButtonRadius() / DRAG_AREA_SCALE;  // 比按钮大一些
    
    qreal distance = std::sqrt(std::pow(pos.x() - center.x(), 2) + 
                              std::pow(pos.y() - center.y(), 2));
    
    return distance <= dragRadius;
}

QList<QPointF> RoundMenuWidget::getScatteredPositions(int itemCount) const
{
    QList<QPointF> positions;
    if (itemCount == 0) return positions;
    
    qreal centerX = width() / 2.0;
    qreal centerY = height() / 2.0;
    qreal spreadRadius = qMin(width(), height()) * 0.35;
    
    // 预定义一些美观的位置（类似第一张图的布局）
    QList<QPointF> predefinedPositions = {
        QPointF(centerX - spreadRadius * 0.8, centerY - spreadRadius * 1.0),  // 左上
        QPointF(centerX + spreadRadius * 0.2, centerY - spreadRadius * 1.2),  // 上方
        QPointF(centerX + spreadRadius * 1.0, centerY - spreadRadius * 0.3),  // 右上
        QPointF(centerX + spreadRadius * 1.2, centerY + spreadRadius * 0.5),  // 右下
        QPointF(centerX + spreadRadius * 0.3, centerY + spreadRadius * 1.1),  // 下方
        QPointF(centerX - spreadRadius * 0.5, centerY + spreadRadius * 0.8),  // 左下
        QPointF(centerX - spreadRadius * 1.1, centerY + spreadRadius * 0.2),  // 左方
        QPointF(centerX - spreadRadius * 0.2, centerY - spreadRadius * 0.6),  // 中左上
        QPointF(centerX + spreadRadius * 0.6, centerY + spreadRadius * 0.1),  // 中右
    };
    
    // 使用预定义位置，如果超出则生成圆形分布
    for (int i = 0; i < itemCount; ++i) {
        if (i < predefinedPositions.size()) {
            positions.append(predefinedPositions[i]);
        } else {
            // 超出预定义位置时，生成圆形分布
            qreal angle = 2 * M_PI * i / itemCount;
            qreal radius = spreadRadius * (1.0 + (i - predefinedPositions.size()) * 0.2);
            QPointF pos(centerX + radius * std::cos(angle),
                       centerY + radius * std::sin(angle));
            positions.append(pos);
        }
    }
      return positions;
}

QList<QPointF> RoundMenuWidget::getCircularPositions(int itemCount) const
{
    QList<QPointF> positions;
    if (itemCount == 0) return positions;
    
    qreal centerX = width() / 2.0;
    qreal centerY = height() / 2.0;
    qreal radius = qMin(width(), height()) * 0.3; // 圆形布局的半径
    
    for (int i = 0; i < itemCount; ++i) {
        qreal angle = 2 * M_PI * i / itemCount + getStartRadian();
        QPointF pos(centerX + radius * std::cos(angle),
                   centerY - radius * std::sin(angle));
        positions.append(pos);
    }
    
    return positions;
}

void RoundMenuWidget::enableRippleEffect(bool enable)
{
    MenuStyleConfig style = getMenuStyle();
    style.enableRippleEffect = enable;
    setMenuStyle(style);
}

void RoundMenuWidget::enableGlowEffect(bool enable)
{
    MenuStyleConfig style = getMenuStyle();
    style.enableGlowEffect = enable;
    setMenuStyle(style);
}

void RoundMenuWidget::enableParticleEffect(bool enable)
{
    MenuStyleConfig style = getMenuStyle();
    style.enableParticleEffect = enable;
    setMenuStyle(style);
}

void RoundMenuWidget::setRippleColor(const QColor& color)
{
    MenuStyleConfig style = getMenuStyle();
    style.rippleColor = color;
    setMenuStyle(style);
}

void RoundMenuWidget::setGlowColor(const QColor& color)
{
    MenuStyleConfig style = getMenuStyle();
    style.glowColor = color;
    setMenuStyle(style);
}

void RoundMenuWidget::drawDragHint(QPainter *painter)
{
    // 绘制一个淡淡的圆圈提示拖动区域
    qreal dragRadius = getDragAreaRadius();
    QPointF center = getCenter();
    
    painter->save();
    
    // 设置淡淡的颜色和虚线样式
    QPen hintPen(QColor(255, 255, 255, 40), 1);
    hintPen.setStyle(Qt::DashLine);
    painter->setPen(hintPen);
    painter->setBrush(Qt::NoBrush);
    
    // 绘制拖动区域圆圈
    painter->drawEllipse(center, dragRadius, dragRadius);
    
    painter->restore();
}

void RoundMenuWidget::addMenuItem(const QString& title, const QString& tooltip, 
                                 const QPixmap& icon, const QPixmap& hoverIcon, const QPixmap& pressedIcon,
                                 const QColor& backgroundColor)
{
    MenuItemData* item = new MenuItemData();
    item->title = title;
    item->tooltip = tooltip;
    item->icon = icon;
    item->hoverIcon = hoverIcon;
    item->pressedIcon = pressedIcon;
    item->backgroundColor = backgroundColor;
    item->isHovered = false;
    item->isPressed = false;
    
    m_menuItems.append(item);
    update();
}
